package com.tmt.im.common.store;

import com.tmt.im.common.pojo.ChatDataKey;
import com.tmt.im.common.pojo.ChatDataPoJo;

import javax.cache.Cache;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/7 15:17
 * @Version 1.0
 **/
public class ChatDataStore extends BaseCacheStoreAdapter<ChatDataKey, ChatDataPoJo> {

    private static final String SELECT_SQL = StoreSqlHelper.generateSqlWithParams("select", ChatDataPoJo.class);
    private static final String INSERT_SQL = StoreSqlHelper.generateSqlWithParams("insert", ChatDataPoJo.class);
    private static final String UPDATE_SQL = StoreSqlHelper.generateSqlWithParams("update", ChatDataPoJo.class);
    private static final String DELETE_SQL = StoreSqlHelper.generateSqlWithParams("delete", ChatDataPoJo.class);

    @Override
    public ChatDataPoJo load(ChatDataKey key) throws CacheLoaderException {
        try (Connection conn = connection()) {
            try (PreparedStatement st = conn.prepareStatement(SELECT_SQL)) {
                st.setLong(1, key.getId());
                try (ResultSet rs = st.executeQuery()) {
                    if (rs.next()) {
                        ChatDataPoJo pojo = new ChatDataPoJo();
                        StoreSqlHelper.initialObject(rs, pojo);
                        return pojo;
                    }
                }
                return null;
            }
        } catch (Exception e) {
            throw new CacheLoaderException("Failed to load: " + key, e);
        }
    }

    @Override
    public void write(Cache.Entry<? extends ChatDataKey, ? extends ChatDataPoJo> entry) throws CacheWriterException {
        try {
            Connection conn = connection();
            ChatDataPoJo val = entry.getValue();
            try (PreparedStatement st = conn.prepareStatement(val.isInsert() ? INSERT_SQL : UPDATE_SQL)) {
                StoreSqlHelper.initPreparedStatement(st, val);
                st.executeUpdate();
            }
        } catch (Exception e) {
            throw new CacheWriterException("Failed to write entry (" + entry + ")", e);
        }
    }

    @Override
    public void delete(Object key) throws CacheWriterException {
        try {
            Connection conn = connection();
            try (PreparedStatement st = conn.prepareStatement(DELETE_SQL)) {
                st.setLong(1, ((ChatDataKey) key).getId());
                st.executeUpdate();
            }
        } catch (SQLException e) {
            throw new CacheWriterException("Failed to delete: " + key, e);
        }
    }

}
